import { HttpClient } from '../utils/http-client';
import type { RequestConfig } from '../types/http';

// 创建HTTP客户端实例
const httpClient = new HttpClient({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
httpClient.addRequestInterceptor({
  onRequest: async (config: RequestConfig) => {
    // 从缓存中获取token
    const token = uni.getStorageSync('token');
    if (token) {
      config.headers = {
        ...config.headers,
        'Authorization': `Bearer ${token}`
      };
    }
    return config;
  },
  onRequestError: (error: any) => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
});

// 添加响应拦截器
httpClient.addResponseInterceptor({
  onResponse: async (response: any) => {
    const { statusCode, data } = response;
    
    // 处理业务逻辑错误
    if (data.code !== 0) {
      const error = new Error(data.message || 'Business logic error');
      return Promise.reject(error);
    }
    
    return response;
  },
  onResponseError: async (error: any) => {
    // 处理401未授权错误
    if (error.statusCode === 401) {
      // 清除token
      uni.removeStorageSync('token');
      // 跳转到登录页
      uni.navigateTo({ url: '/pages/login/index' });
    }
    
    // 显示错误提示
    uni.showToast({
      title: error.message || '网络错误',
      icon: 'none'
    });
    
    return Promise.reject(error);
  }
});

export default httpClient; 